<template>
  <div class="zs-table-page-container">
    <div class="zs-card-sm zs-space-bottom zs-layout-flex-row zs-layout-justify-between">
      <span>
        <el-select :disabled="Boolean(projectName)" @change="queryList" v-model="queryParams.biProjectCode" filterable
          class="zs-select-md zs-space-right-sm" placeholder="项目名称">
          <el-option v-for="item in projectList" :key="item.biProjectCode" :label="item.projectName"
            :value="item.biProjectCode" />
        </el-select>
        <el-date-picker @change="queryList" class="zs-space-right-sm" v-model="queryParams.year" type="year"
          placeholder="年份" :clearable="false" value-format="YYYY" />
        <el-button @click="queryList" class="zs-btn-plain">查询</el-button>
      </span>
      <span class="zs-layout-flex-row">
        <el-button :class="{ 'zs-btn-plain': curCardDataType == 'echarts', 'zs-btn-primary': curCardDataType == 'list' }"
          @click="handleSwitch('list')">表格</el-button>
        <el-button :class="{ 'zs-btn-plain': curCardDataType == 'list', 'zs-btn-primary': curCardDataType == 'echarts' }"
          @click="handleSwitch('echarts')">图形</el-button>
        <el-button class="zs-btn-plain" @click="handleDownload"><el-icon class="el-icon--left">
          <Upload /> 
          </el-icon>导出</el-button>
      </span>
    </div>
    <div v-if="curCardDataType == 'list'" class="zs-card zs-table-page-content">
      <hsTableV2 :loading="tableData.loading" :columns="tableData.columns" :data="tableData.data" :headerHeight="72"
        isMultistageHeader :multistageHeaderData="tableData.multistageData" :rowClassFun="tableData.rowClass" />
      <div class="zs-text-gray-dark zs-text-sm">更新时间：{{ updateTime }}； 能源费：万元；月单方：元/平米</div>
    </div>
    <div v-loading="echartLoading" class="zs-table-page-content" v-else>
      <template v-if="lineEchartData.length > 0">
        <div v-for="item, index in lineEchartData" :key="index" class="zs-card-with-header zs-space-bottom">
          <div class="zs-card-header">
            <i class="icon-b-item zs-icon zs-text-blue zs-space-right-sm"></i>
            <div class="zs-title">{{ item.title || 暂无 }}</div>
          </div>
          <div class="zs-card-content">
            <LineEchart class="zs-layout-grow zs-overflow-auto" :echartId="'myEChartsLineEnergyCosts' + index"
              :echartData="item.energyChartDTO" :isShowAreaStyle="true"></LineEchart>
          </div>
        </div>
        <div class="zs-card-with-header zs-space-bottom">
          <div class="zs-card-header">
            <i class="icon-b-item zs-icon zs-text-blue zs-space-right-sm"></i>
            <div class="zs-title">公区整体费用占比</div>
          </div>
          <div class="zs-card-content zs-layout-flex-row">
            <div v-for="item, index in pieEchartData" :key="index" style="width: 30%;" class="zs-layout-grow ">
              <!-- 饼图 -->
              <PieEchart class="zs-layout-grow zs-overflow-auto" :echartId="'myEChartsPieEnergyCosts' + index"
                :echartData="item" :isHidelegend="index == 0 ? false : true"></PieEchart>
            </div>
          </div>
        </div>
      </template>
      <div v-else class="zs-card">
        <el-empty description="暂无数据" :image-size="100"/>
      </div>
    </div>
  </div>
</template>

<script setup lang="jsx">
import dbPublicApi from '@/api/dbPublic'
import { downloadNewFile } from "@/utils/publicUtils"
import { toThousands } from '@/utils/number-util'
import { useRoute } from 'vue-router'
import { reactive, ref } from "vue"
import LineEchart from "@/components/EchartComponent/LineEchart";
import PieEchart from "@/components/EchartComponent/PieEchart";
import detailApi from '@/api/Manage/Business/detailPages'
let { biProjectCode, updateDate, tabPermi, projectName } = useRoute().query

// 项目下拉选
let projectList = ref([])
const getPorjectList = () => {
  dbPublicApi.queryProjectPcApi({ dataTime: updateDate, resourceKey: tabPermi }).then((res) => {
    if (res.data.code == 200) {
      projectList.value = res.data.data
      if (projectName && !projectList.value.some(el=>el.projectName == decodeURI(projectName))) {
        projectList.value.push({ projectName:decodeURI(projectName), biProjectCode })
      }
    }
  })
}
getPorjectList()
let lineEchartData = ref([]) //折线图表数据
let pieEchartData = ref([]) //折线图表数据
let echartLoading = ref(false)

// 当前卡片内容类型
let curCardDataType = ref('list')

// 查询条件
let queryParams = reactive({
  biProjectCode,
  year: '',
  pageNo: 1,
  pageSize: 10000,
})
// 表格数据
let tableData = reactive({
  loading: false,
  data: [],
  total: 0,
  multistageData: null,
  columns: [
    { key: 'yearmonth', align: "left", title: '科目', isHaveTitle: true, width: 120, minWidth: 120 },
  ],
  rowClass:({rowIndex})=>{
    if (rowIndex == 0) {
      return "db-table-row-blue"
    }
  }
})
// 获取表格数据
let updateTime = ref('')
function queryTableList () {
  tableData.loading = true
  detailApi.energyModuleInfoCardListApi(queryParams).then(res => {
    let resData = res.data
    if (resData.code == 200) {
      tableData.data = resData.data
      let {etlTime:dateUpdate} = resData.data[0] || {dateUpdate:''}
      updateTime.value = dateUpdate || '暂无'
    }
    tableData.loading = false
  })
}

// 获取能源模块详情：图表
async function getEnergyModuleInfoChartData () {
  echartLoading.value = true
  await detailApi.energyModuleInfoLineChartApi(queryParams).then(res => {
    let resData = res.data
    if (resData.code == 200) {
      lineEchartData.value = resData.data
    }
  })
  await detailApi.energyModuleInfoPieChartApi(queryParams).then(res => {
    let resData = res.data
    if (resData.code == 200) {
      pieEchartData.value = resData.data
    }
  })
  echartLoading.value = false
}

function handleSwitch (type) {
  curCardDataType.value = type
  queryList()
}
// 格式化表格列
function initTableColumns () {
  let curMultistageData = {}
  let curHeaderArr = [
    { key: 'overall', title: '公区整体', childrenKey: ['energyCosts', 'ecUnitPrice', 'energyCostsErlier'] },
    { key: 'electricity', title: '公区电费', childrenKey: ['electricCharge', 'dfUnitPrice', 'electricChargeErlier'] },
    { key: 'waterFee', title: '公区水费', childrenKey: ['waterRate', 'sfUnitPrice', 'waterRateErlier'] },
    { key: 'fuelCosts', title: '公区燃料费', childrenKey: ['fuel', 'rlfUnitPrice', 'fuelErlier'] },
  ]
  curHeaderArr.forEach((el, index) => {
    const startIndex = index * 3 + 1
    curMultistageData[el.key] = {
      key: el.key,
      title: el.title,
      childrenKey: el.childrenKey,
      childrenIndex: [startIndex, startIndex + 1, startIndex + 2]
    }
  })
  let windowWidth = document.documentElement.scrollWidth
  let celWidth = (windowWidth - 138 - 120) / (curHeaderArr.length * 3)
  let curColumns = []
  for (var parentKey in curMultistageData) {
    let curKeyArr = curMultistageData[parentKey].childrenKey
    let columnsTitle = [
      { parentKey, key: curKeyArr[0], title: '能源费' },
      { parentKey, key: curKeyArr[1], title: '月单方' },
      { parentKey, key: curKeyArr[2], title: '同比' },
    ]
    columnsTitle.forEach(coloumnItem => {
      let newData = {
        key: coloumnItem.key,
        title: coloumnItem.title,
        parentKey: coloumnItem.parentKey,
        width: celWidth,
        minWidth: celWidth,
        cellRenderer: ({ rowData }, emptyMark) => {
          if (rowData[coloumnItem.key] && rowData[coloumnItem.key] !== '-') {
            return <ElTooltip content={rowData[coloumnItem.key]} placement="top">
              <span class={coloumnItem.title == '同比' ? (rowData[coloumnItem.key].replace('%','') > 0 ? 'zs-text-red' : 'zs-text-green') : ''}>{
                toThousands(rowData[coloumnItem.key])
              }</span>
            </ElTooltip>
          } else {
            return <span>{emptyMark}</span>
          }
        }
      }
      curColumns.push(newData)
    })
  }
  tableData.multistageData = curMultistageData
  tableData.columns = [tableData.columns[0], ...curColumns]
}
// 统一查询
function queryList () {
  initTableColumns()
  if (curCardDataType.value == 'list') {
    queryTableList()
  } else {
    getEnergyModuleInfoChartData()
  }
}
queryList()

// 导出
function handleDownload () {
  if (curCardDataType.value == 'list') {
    detailApi.energyModuleInfoCardExportListApi(queryParams).then(res => {
      downloadNewFile(res.data, `能耗分析列表详情.xls`)
    })
  } else {
    detailApi.energyModuleGraphExportApi(queryParams).then(res => {
      downloadNewFile(res.data, `能耗分析图表详情.xls`)
    })
  }
}
</script>

<style lang="scss" scoped>
</style>
